import { PureComponent } from 'react';
import {
  Scene, OrthographicCamera, BoxGeometry, Line, Vector3,
  Mesh, WebGLRenderer, MeshBasicMaterial,
  MeshLambertMaterial, DirectionalLight
} from 'three';

const drawAxes = scene => {
  const xGeo = new BoxGeometry();
  const xGeoPoints = [
    new Vector3(0, 0, 0),
    new Vector3(6, 0, 0)
  ];
  xGeo.setFromPoints(xGeoPoints);
  const xMat = new MeshBasicMaterial({
    color: 0xff0000
  });
  const xAxis = new Line(xGeo, xMat);
  scene.add(xAxis);

  const yGeo = new BoxGeometry();
  const yGeoPoints = [
    new Vector3(0, 0, 0),
    new Vector3(0, 6, 0)
  ];
  yGeo.setFromPoints(yGeoPoints);
  const yMat = new MeshBasicMaterial({
    color: 0x00ff00
  });
  const yAxis = new Line(yGeo, yMat);
  scene.add(yAxis);

  const zGeo = new BoxGeometry();
  const zGeoPoints = [
    new Vector3(0, 0, 0),
    new Vector3(0, 0, 6)
  ];
  zGeo.setFromPoints(zGeoPoints);
  const zMat = new MeshBasicMaterial({
    color: 0x00ccff
  });
  const zAxis = new Line(zGeo, zMat);
  scene.add(zAxis);
};

const scene = new Scene();

drawAxes(scene);

let renderer = null;

const camera = new OrthographicCamera(-5, 5, 3.75, -3.75, 0.1, 100);
camera.position.set(5, 15, 25);
camera.lookAt(0, 0, 0);

const light = new DirectionalLight();
light.position.set(2, 5, 3);
/**
 * 以下是个人结合教程对于平行光的理解:
 * 位置:
 * 平行光所处位置是平面, 是点(2, 5, 3)所在的平面,
 * 也就是说是从点(2, 5, 3)所在的平面发出, 而不是从点(2, 5, 3)的位置发出, 否则就成点光源了
 * 方向:
 * 照射方向则是点(2, 5, 3)所在平面的法向量方向: [(2, 5, 3), (-2, -5, -3)]
 * 
 * 同时在调整平行光位置的时候可以看出, 两个物体的同方向平面亮度一致,
 * 因此可以看出: 平面亮度与平面位置无关, 而与平面的法向量有关,
 * 也就是说: 只要平面是平行的, 那么得到的光照也一定是相同的
 */
scene.add(light);

const leftGeo = new BoxGeometry(2, 2, 2);
const leftGeoMat = new MeshLambertMaterial({
  color: 0x00ff00
});
const leftMesh = new Mesh(leftGeo, leftGeoMat);
leftMesh.position.x = -3;
scene.add(leftMesh);

const rightGeo = new BoxGeometry(2, 2, 2);
const rightGeoMat = new MeshLambertMaterial({
  color: 0x00ff00
});
const rightMesh = new Mesh(rightGeo, rightGeoMat);
rightMesh.position.x = 3;
scene.add(rightMesh);

const changeLightPosition = () => {
  light.position.set(0, 1.5, 2.5);
  renderer.render(scene, camera);
};

const resetLightPosition = () => {
  light.position.set(2, 5, 3);
  renderer.render(scene, camera);
};

class Index extends PureComponent {

  componentDidMount() {
    renderer = new WebGLRenderer({
      canvas: document.getElementById('mainCanvas')
    });
    renderer.render(scene, camera);

  }

  render() {

    return (
      <div>
        <div>
          <button
            onClick={resetLightPosition}
          >重置位置</button>
          <button
            onClick={changeLightPosition}
          >变更位置</button>
        </div>
        <canvas
          id="mainCanvas"
          width="400"
          height="300"
        />
      </div>
    );
  }
}

export default Index;